<template>
  <div>
    <div class="toptitle"><span class="toptitle-title">1C波形查看</span>
      <div class="toptitle-input">
        <p class="form-top-p">
          <road-input v-model="valuek.startRoadMark" />
        </p>
        <p class="form-top-p">
          <span class="toptitle-title"> — </span>
        </p>
        <p class="form-top-p">
          <road-input v-model="valuek.endRoadMark" />
        </p>
        <p class="form-top-p">
          <el-button type="primary" size="mini" class="form-button" icon="el-icon-search" @click="search1C()">查询</el-button>
        </p>
        <p class="form-top-p">
          <span class="form-cans" @click="showSelect = true">选择查看参数 <i class="el-icon-caret-bottom" /></span>
        </p>
        <div v-show="showSelect" class="pramsSelectDropdown">
          <div class="selectBody">
            <el-checkbox-group v-model="paramSelected">
              <div v-for="param in paramSelects" :key="param.id" class="selectItem">
                <el-checkbox :label="param.id">{{ param.name }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
          <div class="selectBtns h-flex">
            <el-button type="primary" size="mini" @click="setParams()">确认</el-button>
            <el-button type="info" size="mini" @click="showSelect = false">取消</el-button>
          </div>
        </div>
      </div>
    </div>

    <div v-loading="loading" class="analysisContainer" style="height: calc(100%);">
      <div class="analysisChartGroup v-flex">

        <div class="chartTitle">{{ siteName }}{{ nextSiteName }}</div>
        <div id="echart-analysis1C" class="v-flex-elastic" />
        <div class="tableContainer widthPage" style="height: 50px;padding-left:20px;">
          <ul class="block sliderbox">
            <li>第1页</li>
            <li>
              <el-slider
                v-model="queryParams.page"
                :min="1"
                :max="Math.ceil(total/queryParams.size)"
                @change="chartSlides" />
            </li>
            <li>
              {{ Math.ceil(total/queryParams.size) }}页
            </li>
            <li>
              <Pagination
                :hidden="false"
                style="background: transparent;"
                layout="total, prev, next, jumper"
                :total="total"
                :page.sync="queryParams.page"
                :size.sync="queryParams.size"
                @pagination="getC1DataByParams(queryParams)" />
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import { findDetailWaveform } from '@/api/cms/detect-data'
export default {
  name: 'Analysis1C',
  props: {
    deviceCode: {
      type: String,
      default: ''
    },
    devClassCode: {
      type: String,
      default: ''
    },
    timeAxisType: {
      type: String, // 当前时间轴类型，用于判断是否调用接口
      default: 'default'
    },
    date: {
      type: String, // 时间轴当前选择的时间
      default: ''
    },
    lineCode: {
      type: String,
      default: ''
    },
    detectJobId: {
      type: String,
      default: ''
    },
    active: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      siteName: '',
      nextSiteName: '',
      valuek: {
        startRoadMark: '',
        endRoadMark: ''
      },
      valueX: 0,
      formz: {
        selectLin: [
          {
            value: '选项1',
            label: '' + this.PHMTESTDATA.phmvariable.line[0] + ''
          }, {
            value: '选项2',
            label: '' + this.PHMTESTDATA.phmvariable.line[1] + ''
          }, {
            value: '选项3',
            label: '' + this.PHMTESTDATA.phmvariable.line[2] + ''
          }, {
            value: '选项4',
            label: '' + this.PHMTESTDATA.phmvariable.line[3] + ''
          }, {
            value: '选项5',
            label: '' + this.PHMTESTDATA.phmvariable.line[4] + ''
          }, {
            value: '选项6',
            label: '' + this.PHMTESTDATA.phmvariable.line[5] + ''
          }
        ],
        selectsuju: [
          {
            value: '选项1',
            label: '2019-03-04-兰新客专-下行'
          }
        ]
      },
      loading: false,
      queryParams: {
        page: 1,
        size: 30
      },
      detectData: [{
        detectDate: ''
      }],
      paramSelects: [{
        name: '导高-相机',
        id: 'guideHeight1'
      }, {
        name: '拉出值-相机',
        id: 'staggers1'
      }, {
        name: '水平硬点',
        id: 'hardPoint'
      }, {
        name: '弓网接触力',
        id: 'stress'
      }, {
        name: '燃弧',
        id: 'arcing'
      }, {
        name: '接触网电压',
        id: 'pressure'
      }, {
        name: '导高-雷达',
        id: 'guideHeight2'
      }, {
        name: '拉出值-雷达',
        id: 'staggers2'
      }, {
        name: '支柱号',
        id: 'pillarNum'
      }],
      paramSelected: ['guideHeight1', 'staggers1', 'hardPoint', 'stress'],
      timeSort: '',
      reverse: false,
      timer: false,
      showSelect: false,
      analysisChart: null,
      pillarAxis: [], // 支柱号坐标轴
      chartDatas: {
        detectDate: [], // 横坐标-时间-支柱
        roadMark: [], // 横坐标-公里标-锚段
        guideHeight1: [], // 导高-相机
        staggers1: [], // 拉出值-相机
        hardPoint: [], // 水平硬点
        stress: [], // 弓网接触力
        arcing: [], // 燃弧
        pressure: [], // 接触网电压
        guideHeight2: [], // 导高-雷达
        staggers2: [], // 拉出值-雷达
        pillarNum: [] // 支柱号
      },
      dateVal: this.date,
      total: 0
    }
  },
  watch: {
    date(val) {
      this.dateVal = val
      if (this.devClassCode === '100') {
        // 1C锚段才有时间轴
        this.queryParams.detectDate = val
        this.timeAxisType === '1C' && this.getC1DataByParams(this.queryParams)
      }
    },
    active(val) {
      if (val) {
        this.queryParams = {
          page: 1,
          size: 30,
          detectJobId: this.detectJobId
        }
        this.valuek = {
          startRoadMark: '',
          endRoadMark: ''
        }
        this.paramSelected = ['guideHeight1', 'staggers1', 'hardPoint', 'stress']
        this.getC1DataByParams(this.queryParams)
      }
    }
  },
  mounted() {
    // this.getC1DataByParams(this.queryParams)
    // 监听屏幕变化，改变echarts尺寸
    const _this = this
    window.addEventListener('resize', function() {
      _this.$nextTick(_ => {
        if (!this.analysisChart) {
          return
        }
        _this.analysisChart.resize()
      })
    })
  },
  beforeDestroy() {
    if (!this.analysisChart) {
      return
    }
    this.analysisChart.dispose()
    this.analysisChart = null
  },
  methods: {
    setParams() {
      this.showSelect = false
      this.initAnalysisChart(this.sortBySelected(this.chartDatas))
    },
    getC1DataByParams(param) {
      this.loading = true
      this.siteName = ''
      this.nextSiteName = ''
      findDetailWaveform(param).then(response => {
        this.loading = false
        // console.log('c1图形数据', response)
        this.clearChartDatas()
        if (response.data && response.data.records) {
          let lastNum = '' // 上一个支柱号
          response.data.records.forEach(item => {
            this.siteName = item.siteName
            if (lastNum !== item.pillarNum) {
              this.pillarAxis.push(item.pillarNum)
              lastNum = item.pillarNum
            } else {
              this.pillarAxis.push('')
            }

            for (const key in this.chartDatas) {
              if (key === 'roadMark') {
                this.chartDatas[key].push(this.formatRoad(item[key]))
              } else {
                this.chartDatas[key].push(item[key] || 0)
              }
            }
          })
          this.total = response.data.total
        }
        this.initAnalysisChart(this.sortBySelected(this.chartDatas))
      })
    },
    clearChartDatas() {
      this.pillarAxis = []
      for (const key in this.chartDatas) {
        this.chartDatas[key] = []
      }
      this.total = 0
    },
    sortBySelected(datas) {
      // 数据按参数筛选
      const paramSelected = this.paramSelected
      const data = {}
      paramSelected.forEach(item => {
        if (datas[item]) {
          const name = this.paramSelects.filter(e => {
            return e.id === item
          })[0].name
          data[name] = datas[item]
        }
      })
      data['detectDate'] = datas['detectDate']
      data['roadMark'] = datas['roadMark']
      return data
    },
    initAnalysisChart(datas) {
      console.log('datasdatasdatasdatasdatasdatasdatasdatasdatasdatasdatas', datas)
      if (!this.analysisChart) {
        this.analysisChart = echarts.init(document.getElementById('echart-analysis1C'))
      }
      let index = 0
      const length = Object.keys(datas).length - 2
      const height = (90 / length).toFixed(2)
      const titles = []
      const grid = []
      const xAxis = []
      const yAxis = []
      const series = []
      const singleAxis = []
      const dataZoom = []
      for (const key in datas) {
        if (key !== 'detectDate' && key !== 'roadMark') {
          titles.push({
            textAlign: 'left',
            text: key,
            top: (height * index) + '%',
            left: 20,
            textStyle: {
              fontSize: 12,
              color: 'black',
              fontWeight: 'normal'
            }
          })
          grid.push({
            height: height + '%',
            top: (2 + height * index) + '%',
            show: true,
            borderColor: 'rgba(64, 158, 255, 0.1)',
            right: 50,
            left: 100,
            bottom: 20
          })
          xAxis.push({
            show: index === (length - 1) ? 1 : 0,
            type: 'category',
            axisLine: {
              lineStyle: {
                color: 'black'
              }
            },
            triggerEvent: true,
            axisLabel: {
              showMinLabel: true,
              showMaxLabel: true,
              interval: 0,
              rotate: 30
            },
            boundaryGap: false,
            gridIndex: index,
            // data: ['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01']
            data: datas.roadMark
          })
          yAxis.push({
            type: 'value',
            boundaryGap: true,
            scale: true,
            splitLine: {
              show: false
            },
            axisLabel: {
              showMinLabel: false,
              showMaxLabel: false
            },
            axisLine: {
              lineStyle: {
                color: 'black'
              }
            },
            gridIndex: index
          })
          series.push({
            name: key,
            type: 'line',
            smooth: true,
            data: datas[key],
            yAxisIndex: index,
            xAxisIndex: index
          })
          index++
        }
      }
      singleAxis.push({
        left: 120,
        right: 50,
        type: 'category',
        boundaryGap: false,
        data: this.pillarAxis,
        top: '42%',
        height: 20,
        splitLine: {
          show: false
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          interval: 1,
          color: 'black',
          fontSize: 14
        }
      })
      // series.push({
      //   name: '支柱号',
      //   coordinateSystem: 'singleAxis',
      //   type: 'scatter',
      //   data: []
      // })
      const option = {
        title: titles,
        grid: grid,
        tooltip: {
          trigger: 'axis',
          transitionDuration: 0,
          confine: true,
          bordeRadius: 4,
          borderWidth: 1,
          borderColor: '#333',
          backgroundColor: 'rgba(255,255,255,0.9)',
          textStyle: {
            fontSize: 14,
            lineHeight: 32,
            color: 'black'
          },
          formatter: function(params, ticket, callback) {
            params.sort((a, b) => a['axisIndex'] > b['axisIndex'] ? 1 : -1)
            let res = params[0].name
            for (let i = 0, l = params.length; i < l; i++) {
              res += `<br/><span style="color:${params[i].color};">` + params[i].seriesName + ' : ' + params[i].value + '</span>'
            }
            return res
          }
        },
        axisPointer: {
          type: 'shadow',
          link: {
            xAxisIndex: 'all'
          }
        },
        xAxis: xAxis,
        yAxis: yAxis,
        singleAxis: singleAxis,
        series: series
      }
      this.analysisChart.setOption(option, true)
    },
    chartSlides() {
      this.getC1DataByParams(this.queryParams)
    },
    setDatePicker() {
      // 根据时间范围查询， 选择范围时删除detectDate
      const timeSort = this.timeSort
      if (timeSort) {
        this.queryParams.startDate = timeSort[0]
        this.queryParams.endDate = timeSort[1]
        delete this.queryParams.detectDate
      } else {
        delete this.queryParams.startDate
        delete this.queryParams.endDate
      }
      this.getC1DataByParams(this.queryParams)
    },
    search1C() {
      const param = {}
      if (this.detectJobId) {
        param.detectJobId = this.detectJobId
      }
      if (this.valuek.startRoadMark) {
        param.startRoadMark = this.reFormatRoad(this.valuek.startRoadMark)
      }
      if (this.valuek.endRoadMark) {
        param.endRoadMark = this.reFormatRoad(this.valuek.endRoadMark)
      }
      this.queryParams.page = 1
      this.getC1DataByParams(param)
    },
    // formatRoad(val) {
    //   if (!val) return ''
    //   let value = val.toString()
    //   if (value.startsWith('-')) {
    //     value = '-K' + value.slice(1).replace(/\./, '+')
    //   } else {
    //     value = 'K' + value.replace(/\./, '+')
    //   }
    //   if (value.includes('+')) {
    //     const int = value.slice(0, value.indexOf('+'))
    //     const decimal = value.slice(value.indexOf('+') + 1)
    //     value = int +
    //       '+' +
    //       (decimal.length <= 3 ? decimal + '0'.repeat(3 - decimal.length) : decimal.slice(0, 3)) +
    //       '.' +
    //       (decimal.length <= 3 ? '00' : decimal.slice(3, 6) + '0'.repeat(5 - decimal.length > 0 ? 5 - decimal.length : 0))
    //   } else {
    //     value = value + '+000.00'
    //   }
    //   return value
    // },
    reFormatRoad(str) {
      str = str.toUpperCase()
      if (str.indexOf('+') > -1) {
        return parseInt(str.split('+')[0].replace('K', '')) + str.split('+')[1] * 1 / 1000 // 12+230、K12+230
      } else {
        return Number(str.replace('K', '')) // 12.23、K12.23
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .analysisContainer {
    padding-top: 20px;
    overflow: auto;
    color: white;

    .form-button {
      float: none;
    }

    .analysisChartGroup {
      position: relative;
      z-index: 1;
      height: 100%;
    }

    .phwidth {
      display: inline-block;
      width: 150px;
    }

    .chartTitle {
      position: absolute;
      top: 40px;
      z-index: 5;
      width: 100%;
      font-size: 14px;
      font-weight: normal;
      line-height: 24px;
      text-align: center;

      span {
        cursor: pointer;
      }
    }
  }
.toptitle{
  height: 50px;
  display: flex;
  align-items: center;
  margin: 0;
  padding: 10px;
  background: #3a475b;
  color: white;
  img{
    height: 14px;
    margin-right: 8px;
  }
}
.form-top-p{
  margin: 0;
  ::v-deep .el-input__icon{
    line-height: 33px;
  }
}
.form-cans {
      display: inline-block;
      height: 28px;
      padding: 0 5px;
      font-size: 12px;
      line-height: 28px;
      color: #fff;
      vertical-align: bottom;
      background-color: #409eff;
      border-color: #409eff;
      border-radius: 4px;
    }
.form-cans:hover{
  cursor: pointer;
}
.toptitle-input{
  margin-left: 40px;
}
.toptitle-title{
  color: white;
}
.sliderbox{
  display: flex;
  justify-content:space-between;
  align-items: center;
  li:nth-child(1){
    margin-right: 10px;
    color: #666;
  }
  li:nth-child(2){
    flex: 1;
    margin-right: 10px;
  }
  li:nth-child(3){
    margin:0 10px;
    color: #666;
  }
}
.pramsSelectDropdown {
      position: absolute;
      top: 60px;
      left: 620px;
      z-index: 90;
      width: 200px;
      padding: 15px 15px 50px;
      border: 1px solid #409eff;
      background: white;
      animation: slideUp ease-out 0.3s;

      .selectItem {
        margin-bottom: 5px;
        line-height: 20px;
      }

      .el-checkbox {
        color: black;
      }

      .selectBody {
        height: 200px;
        overflow: auto;
      }

      .selectBtns {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        padding: 11px 0;
      }
    }
</style>
